package com.hl.toolkit.pay.controller;

import com.tycoin.common.bean.PageInfo;
import com.tycoin.common.jpa.PropertyFilter;
import com.tycoin.common.jpa.SpecificationUtils;
import com.tycoin.common.repository.AbstractRepository;
import com.util.IpUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Validator;
import java.util.*;


public abstract class AbstractController {
    protected static final String SEARCH_KEY = "search_";

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 验证Bean实例对象
     */
     protected Validator validator;

    
    /**
     * 获取IP地址
     *
     * @param request
     * @return
     */
    protected String getIpAddr(HttpServletRequest request) {
        return IpUtils.getIpAddr(request);
    }

    protected String getRequestUrl(HttpServletRequest request) {
        StringBuffer sb = request.getRequestURL();
        String queryString = request.getQueryString();
        if (StringUtils.isNotEmpty(queryString)) {
            sb.append("?").append(queryString);
        }
        return sb.toString();
    }

    protected String getAllParam(HttpServletRequest request) {
        List<String> nameList = new ArrayList<String>();
        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            nameList.add(name);
        }

        // Collections.sort(nameList, new Comparator<String>() {
        // public int compare(String o1, String o2) {
        // return o1.compareTo(o2);
        // }
        // });

        StringBuffer info = new StringBuffer("params:");
        for (String name : nameList) {
            String value = request.getParameter(name);
            info.append("<").append(name).append("=");
            info.append(value).append(">");
            if (names.hasMoreElements()) {
                info.append(",");
            }
        }
        return info.toString();
    }
    
    
	public String  isNotparam(Map<String,String> map){
		String result="";
 		for (Map.Entry<String, String> entry : map.entrySet()) {  
  		     if(!StringUtils.isNotBlank(entry.getValue())){
	             result="{\"result_code\":\"201\",\"return_"
	             		+ "msg\":\""+entry.getKey()+"参数不能为空\"}";
	        }
		}  
 		return result;
		
	}
	
	public Map<String,Object>  isNotparamReturnMap(Map<String,String> map){
		Map<String, Object> mapCode=new HashMap<>();
 		for (Map.Entry<String, String> entry : map.entrySet()) {  
  		     if(!StringUtils.isNotBlank(entry.getValue())){
  		    	mapCode.put("code", 201);
  		    	mapCode.put("msg", entry.getKey()+"参数不能为空");	             
	        }
		}  
		return mapCode;
		
		
		
  	}
	
	/**
	 * 从request中获得参数Map，并返回可读的Map
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<String,String> getAllRequestParam(HttpServletRequest request) {
		// 参数Map
		Map properties = request.getParameterMap();
		// 返回值Map
		Map returnMap = new HashMap();
		Iterator entries = properties.entrySet().iterator();
		Map.Entry entry;
		String name = "";
		String value = "";
		while (entries.hasNext()) {
			entry = (Map.Entry) entries.next();
			name = (String) entry.getKey();
			Object valueObj = entry.getValue();
			if(null == valueObj){
				value = "";
			}else if(valueObj instanceof String[]){
				String[] values = (String[])valueObj;
				for(int i=0;i<values.length;i++){
					value = values[i] + ",";
				}
				value = value.substring(0, value.length()-1);
			}else{
				value = valueObj.toString();
			}
			returnMap.put(name, value);
		}
		return returnMap;
	}
	
	/**
	 * 验证请求参数不为空  返回
	 * @param map
	 * @return
	 */
	public Map<String,String>  verifyRequestParameters(HttpServletRequest request){
		Map<String,String> map=getAllRequestParam(request);
		Map<String, String> mapCode=new HashMap<>();
 		for (String key : map.keySet()) {  
  		     if(StringUtils.isNotBlank(key)){
  		    	mapCode.put(key, map.get(key));  		    		             
	        }
		}  
		return mapCode;		
  	}
 
	 /**
     * 根据请求获取查询结果
     *
     * @param request
     * @param pageInfo
     * @param abstractRepository
     * @return
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected <T> Page<T> find(final HttpServletRequest request, final PageInfo pageInfo, final AbstractRepository abstractRepository) {
        Specification<T> specification = getSpecification(request);
        PageRequest pageRequest = PageInfo.getPageRequest(pageInfo);
        Page<T> page = abstractRepository.findAll(specification, pageRequest);
        return page;
    }
    /**
     * 根据请求获取查询对象
     *
     * @param request
     * 
     * @param <T>
     * @return
     */
    protected static <T> Specification<T> getSpecification(final HttpServletRequest request) {
        List<PropertyFilter> pfList = getPropertyFilters(request);
        return SpecificationUtils.getSpecification(pfList);
    }

    /**
     * 根据请求获取查询对象
     *
     * @param request
     * @param <T>
     * @return
     */
    protected static <T> List<PropertyFilter> getPropertyFilters(final HttpServletRequest request) {
        Map<String, String> searchMap = getParametersStartingWith(request);
        return getPropertyFilters(searchMap);
    }
    

    /**
     * 根据过滤条件获取查询对象
     *
     * @param map
     * @param <T>
     * @return
     */
    protected static <T> List<PropertyFilter> getPropertyFilters(final Map<String, String> map) {
        List<PropertyFilter> pfList = new ArrayList<PropertyFilter>();
        for (String key : map.keySet()) {
            if (StringUtils.isNotEmpty(map.get(key))) {
                pfList.add(new PropertyFilter(key, map.get(key)));
            }
        }
        return pfList;
    }
    /**
     * 根据请求获取过滤条件
     *
     * @param request
     * @return
     */
    protected static Map<String, String> getParametersStartingWith(final HttpServletRequest request) {
        return getParametersStartingWith(request, SEARCH_KEY);
    }

    /**
     * 取得带相同前缀的Request Parameters.
     * <p/>
     * 返回的结果Parameter名已去除前缀.
     */
    protected static Map<String, String> getParametersStartingWith(final HttpServletRequest request, final String prefix) {
        String prefixStr = StringUtils.trimToEmpty(prefix);
        Map<String, String> params = new TreeMap<String, String>();

        Enumeration<String> paramNames = request.getParameterNames();
        while (paramNames != null && paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            if (StringUtils.isEmpty(prefixStr) || paramName.startsWith(prefixStr)) {
                String unprefixed = paramName.substring(prefixStr.length());
                String[] values = request.getParameterValues(paramName);
                if (values == null || values.length == 0) {
                    // Do nothing, no values found at all.
                } else {
                    params.put(unprefixed, values[0]);
                }
            }
        }
        return params;
    }

    
}
